﻿using Loogn.OrmLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TaskCaller.Models;
using TaskCaller.Models.entity;
using TaskCaller.Repositories;

namespace TaskCaller.Services
{
    public class DelayTaskService
    {
        private readonly IDelayTaskRepository _delayTaskRepository;
        public DelayTaskService(IDelayTaskRepository delayTaskRepository)
        {
            _delayTaskRepository = delayTaskRepository;
        }



        public ResultObject Edit(DelayTask m)
        {
            if (string.IsNullOrEmpty(m.Url))
            {
                return new ResultObject("url不能为空");
            }
            if (m.Id > 0)
            {

                var flag = _delayTaskRepository.Update(m);
                return new ResultObject(flag);
            }
            else
            {
                if (m.TriggerTime <= DateTime.Now)
                {
                    return new ResultObject("触发时间不正确");
                }
                var flag = _delayTaskRepository.Add(m);
                return new ResultObject(flag);
            }
        }

        public OrmLitePageResult<DelayTask> SearchList(string name, int pageIndex, int pageSize)
        {
            return _delayTaskRepository.SearchList(name, pageIndex, pageSize);
        }

        public List<DelayTask> SelectReadyList(DateTime beginTime, DateTime endTime)
        {
            return _delayTaskRepository.SelectReadyList(beginTime, endTime);
        }
        public List<DelayTask> SelectByIds(List<long> ids)
        {
            return _delayTaskRepository.SelectByIds(ids);
        }

        public DelayTask SingleById(long id)
        {
            return _delayTaskRepository.SingleById(id);
        }

        public ResultObject Delete(long id)
        {
            var flag = _delayTaskRepository.Delete(id);
            return new ResultObject(flag);
        }

        public bool Retry(DelayTask task)
        {
            //不重试
            if (task.MaxRetryCount < 0)
            {
                return false;
            }
            //达到了最大次数
            if (task.ExecCount >= task.MaxRetryCount && task.MaxRetryCount > 0)
            {
                return false;
            }
            task.TriggerTime = DateTime.Now.AddSeconds(task.RetrySeconds);
            _delayTaskRepository.RetryUpdate(task);
            return true;
        }
    }
}
